/**
 * 
 */
package com.m7012e.a_remote.commons;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

import com.m7012e.a_remote.communication.MulticastMessage;

/**
 * @author leoj
 *
 */
public enum ARemoteMulticastSender{
	INSTANCE;
	
	private MulticastSocket _multiSock;
	private InetAddress _group;
	private int _port;

	ARemoteMulticastSender(String ipAddress, int port){
		_port = port;
		try {
			_group = InetAddress.getByName(ipAddress);	
			_multiSock = new MulticastSocket();
			_multiSock.joinGroup(_group);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 
	 */
	ARemoteMulticastSender(){
		this("224.0.0.251", 8706);
	}
	
	public void sendMessage(MulticastMessage m) throws IOException{
		ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
		ObjectOutputStream objOutput = new ObjectOutputStream(output);
		objOutput.writeObject(m); 
		objOutput.flush();
		
		byte[] buf = output.toByteArray();
		DatagramPacket packet = new DatagramPacket(buf, 0,buf.length, _group, _port);
		_multiSock.send(packet);
	}
}
